package com.block.job.service.channelcost;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.db.entity.ChannelCountInfo;
import com.block.db.mapper.ChannelCountInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;

@Service
public class ChannelXiaoMiCostService {


    public static String getAccountInfoUrl = "https://api.e.mi.com/openapi/account/balance";

    public static String SecretKey = "TLJohcbBYixyRgTp";
    public static String SignId = "1db245c7156f1c2244ca19f51f7b12bc";

    public static Integer customerId = Integer.valueOf(689442);

    @Autowired
    TransactionTemplate transactionTemplate;
    @Resource
    ChannelCountInfoMapper channelCountInfoMapper;

    public void getAccountCost(){

        String preSign = StrUtil.format("customerId{}signId{}{}", customerId, SignId, SecretKey);
        String sign = SecureUtil.md5(preSign).toLowerCase();

        String uri = StrUtil.format("?customerId={}&signId={}&sign={}", customerId, SignId, sign);
        String requestUrl = getAccountInfoUrl+uri;

        String result = HttpUtil.createGet(requestUrl).execute().body();

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        if (code == 0){

            JSONObject data = resultObject.getJSONObject("result");
            BigDecimal dayConsume = data.getBigDecimal("dayConsume");

            transactionTemplate.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus status) {

                    String dateInfo = LocalDate.now().toString();
                    ChannelCountInfo channelCountInfo = channelCountInfoMapper.getEntityByChannelCodeAndDateInfo("xiaomi", dateInfo);
                    if (ObjectUtil.isNotEmpty(channelCountInfo)){
                        ChannelCountInfo updateEntity = new ChannelCountInfo();
                        updateEntity.setId(channelCountInfo.getId());
                        updateEntity.setUvCost(dayConsume);
                        channelCountInfoMapper.updateById(updateEntity);
                    }
                    return null;
                }
            });
        }
        return;
    }


}
